package co.yixiang.modules.system.rest;

import co.yixiang.annotation.AnonymousAccess;
import co.yixiang.aop.log.Log;
import co.yixiang.modules.shop.domain.YxUser;
import co.yixiang.modules.shop.repository.YxUserRepository;
import co.yixiang.modules.shop.service.mapper.YxUserMapper;
import co.yixiang.modules.system.domain.*;
import co.yixiang.modules.system.repository.UserRepository;
import co.yixiang.modules.system.repository.UserShopRepository;
import co.yixiang.modules.system.service.UserShopService;
import co.yixiang.modules.system.service.dto.UserShopDto;
import co.yixiang.modules.system.service.dto.UserShopQueryCriteria;
import com.alibaba.fastjson.JSON;
import com.alipay.api.domain.ShopInfo;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
* @author lijuhunze
* @date 2020-04-28
*/
@Api(tags = "商户入驻管理")
@RestController
@RequestMapping("/api/userShop")
public class UserShopController {

@Resource
private YxUserRepository yxUserRepository;

    @Resource
    private UserRepository userRepository;

    @Resource
    private UserShopRepository userShopRepository;

    private final UserShopService userShopService;

    private final PasswordEncoder passwordEncoder;

    public UserShopController(UserShopService userShopService, PasswordEncoder passwordEncoder) {
        this.userShopService = userShopService;
        this.passwordEncoder = passwordEncoder;
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('userShop:list')")
    public void download(HttpServletResponse response, UserShopQueryCriteria criteria) throws IOException {
        userShopService.download(userShopService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询商户入驻")
    @ApiOperation("查询商户入驻")
  //  @PreAuthorize("@el.check('userShop:list')")
    @AnonymousAccess
    public ResponseEntity<Object> getUserShops(UserShopQueryCriteria criteria, Pageable pageable){


        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        Map<String, Object> map = userShopService.queryAll(criteria, pageable);

        stringObjectHashMap.put("code",200);
        stringObjectHashMap.put("message",map);
        return ResponseEntity.ok(stringObjectHashMap);

    }

    @PostMapping
    @Log("新增商户入驻")
    @ApiOperation("新增商户入驻")
    @PreAuthorize("@el.check('userShop:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody UserShop resources){


        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code",200);
        stringObjectHashMap.put("message",userShopService.create(resources));
        return ResponseEntity.ok(stringObjectHashMap);
    }

    @PutMapping
    @Log("修改商户入驻")
    @ApiOperation("修改商户入驻")
    @PreAuthorize("@el.check('userShop:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody UserShop resources){
        //
        if(resources.getStatus() == -1){
            //long  d = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
//            Timestamp ts = new Timestamp(System.currentTimeMillis());
//            int time = (int) ((ts.getTime())/1000);;
//            resources.setFailTime(Integer.parseInt(String.valueOf(time)));
            resources.setFailTime(LocalDateTime.now());
        }else if(resources.getStatus() == 1){
            //long  d = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
//            Timestamp ts = new Timestamp(System.currentTimeMillis());
//            int time = (int) ((ts.getTime())/1000);;
//            resources.setSuccessTime(time);
            resources.setSuccessTime(LocalDateTime.now());
        }
        userShopService.update(resources);




        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code",200);
        return ResponseEntity.ok(stringObjectHashMap);
    }

    @Log("删除商户入驻")
    @ApiOperation("删除商户入驻")
    @PreAuthorize("@el.check('userShop:del')")
    @DeleteMapping
    public ResponseEntity<Object> deleteAll(@RequestBody Long[] ids) {
        userShopService.deleteAll(ids);
        Map map = new HashMap();
        map.put("code",200);
        return new ResponseEntity<>(map,HttpStatus.OK);
    }


    @Log("删除单个商户入驻")
    @ApiOperation("删除单个商户入驻")
    @PreAuthorize("@el.check('userShop:del')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Object> delete(@PathVariable long id) {
        userShopService.deleteAll(new Long[]{id});
        Map map = new HashMap();
        map.put("code",200);
        return new ResponseEntity<>(map,HttpStatus.OK);
    }



    @Log("新增商户账户")
    @ApiOperation("新增商户账户")
    @PostMapping("createShopper")
    @AnonymousAccess
    //@PreAuthorize("@el.check('admin','user:add')")
    public ResponseEntity<Object> createShopper(@RequestBody Map<String,Object> map){


        //{businessId=13, email=null, enabled=true, nickName=小飞侠, password=111111, phone=18761879594, sex=0, status=1, username=xiaofeixia}
        System.out.println(map);
        String s = JSON.toJSONString(map);
        User user = JSON.parseObject(s, User.class);
        Long businessId = Long.parseLong(map.get("businessId").toString());
        user.setId(businessId);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
        Role role = new Role();
        role.setId(4L);
        Optional<UserShop> byId2 = userShopRepository.findById(businessId);
        UserShop userShop1 = byId2.get();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        Optional<YxUser> byId = yxUserRepository.findById(userShop1.getUser().getUid());
        UserShop userShop = new UserShop();
        userShop.setId(businessId);
        userShop.setUser(byId.get());
        stringObjectHashMap.put("code",200);
        stringObjectHashMap.put("message",userShopService.createShopper(userShop));
        return ResponseEntity.ok(stringObjectHashMap);

    }
}